import {onMounted, onUnmounted}from 'vue'
import type {Ref} from 'vue'
// 第一个参数是一个ref响应dom节点，第二个参数是点击外部的回调函数
const useClickOutside = (elementRef: Ref<undefined|HTMLElement>, callback: (e:MouseEvent) => void) => {
  const handler = (e:MouseEvent)=>{
     if (elementRef.value && e. target) {
        // 判断点击的元素是否在ref元素内
       if(!elementRef.value.contains(e.target as HTMLElement)) {
          callback(e)
       }
     }
  }
  onMounted(() => {
    document.addEventListener('click', handler)
  })
  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
}
export default useClickOutside